package com.rambo.xpd.base.handler;

import com.rambo.xpd.base.vo.StudentGridlb;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


/**
 * Create by Rambo on 2017/5/10
 **/
public class SAXHandler extends DefaultHandler {
    private List<StudentGridlb> studentGridlbList = null;
    private StudentGridlb studentGridlb = null;
    private String tagName;

    @Override
    public void startDocument() throws SAXException {
        System.out.println("---->startDocument() is invoked...");
        studentGridlbList = new ArrayList<>();
    }

    @Override
    public void endDocument() throws SAXException {
        System.out.println("---->endDocument() is invoked...");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.println("-------->startElement() is invoked...,qName:" + qName);
        if ("studentGridlb".equals(qName)) {
            this.studentGridlb = new StudentGridlb();
        }
        this.tagName = qName;
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.println("-------->endElement() is invoked...");
        if (qName.equals("studentGridlb")) {
            this.studentGridlbList.add(this.studentGridlb);
        }
        this.tagName = null;
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        System.out.println("------------>characters() is invoked...");

        if (this.tagName != null) {
            String contentText = new String(ch, start, length);
            if (this.tagName.equals("stu_id")) {
                this.studentGridlb.setStu_id(contentText);
            }
            if (this.tagName.equals("stu_name")) {
                this.studentGridlb.setStu_name(contentText);
            }
            if (this.tagName.equals("stu_age")) {
                this.studentGridlb.setStu_age(Integer.parseInt(contentText));
            }
            if (this.tagName.equals("stu_birthday")) {
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    this.studentGridlb.setStu_birthday(format.parse(contentText));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public List<StudentGridlb> getStudentGridlbList() {
        return studentGridlbList;
    }

    public void setStudentGridlbList(List<StudentGridlb> studentGridlbList) {
        this.studentGridlbList = studentGridlbList;
    }
}